// import { useStorage } from '@vueuse/core'
import { encode, decode } from 'js-base64'
import md5 from 'js-md5'
import { LoginState } from 'types/models'
import { useSystemMenu } from '@/store'
import { getVerifyCode, login } from '@/services/index'

export function useLogin(loginForm: LoginState, rememberPassBox: any) {
  const store = useSystemMenu()
  const checkRememberPassword = () => {
    const loginRemInfo = localStorage.getItem('loginRemInfo')
    if (loginRemInfo) {
      const jsonInfo = JSON.parse(decode(loginRemInfo))
      loginForm.account = jsonInfo.account
      loginForm.password = jsonInfo.password
      // console.log(loginForm, 'loginFormLoginFormLoginForm')
      // eslint-disable-next-line no-param-reassign
      rememberPassBox = true
    }
  }

  // 判断是否需要记住账号密码
  const checkNeedRememberPassword = () => {
    if (rememberPassBox) {
      const info = {
        account: loginForm.account,
        password: loginForm.password
      }
      localStorage.setItem('loginRemInfo', encode(JSON.stringify(info)))
      // loginForm = useStorage('loginRemInfo', {...info})
    } else {
      localStorage.removeItem('loginRemInfo')
    }
  }

  const getImageVerifyCode = async () => {
    const res = await getVerifyCode()
    if (res.code === 200) {
      loginForm.captchaId = res.data.key
      loginForm.vcodeImg = res.data.b64s
    }
    console.log(res)
  }

  const submitLogin = async () => {
    console.log(md5(loginForm.password).toLocaleLowerCase())
    loginForm.loading = true

    const { account } = loginForm
    const password = md5(loginForm.password).toLocaleLowerCase()

    const res = await login({ account, password })
    loginForm.loading = false
    if (res?.code === 200) {
      localStorage.setItem(
        'token',
        JSON.stringify({
          ...res,
          account: loginForm.account
        })
      )
      localStorage.removeItem('pinia')
      store.fetchSystemList()
    } else {
      // warnMessage('用户名或密码输入有误，请重新输入')
      getImageVerifyCode()
    }
  }

  return {
    checkRememberPassword,
    checkNeedRememberPassword,
    getImageVerifyCode,
    submitLogin
  }
}
